﻿using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;

namespace eslib.nnp5.serializer
{
    /// <summary>
    /// 使用ODATA xml序列化
    /// </summary>
    public class ODATASerializer : ISerializer
    {
        public T Deserialize<T>(byte[] buf) where T : new()
        {
            string xml = Encoding.UTF8.GetString(buf);
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            using TextReader reader = new StringReader(xml);
            return (T)serializer.Deserialize(reader);
        }

        public object Deserialize(Type t, byte[] buf)
        {
            string xml = Encoding.UTF8.GetString(buf);
            XmlSerializer serializer = new XmlSerializer(t);
            using TextReader reader = new StringReader(xml);
            return serializer.Deserialize(reader);
        }

        public byte[] Serialize(object obj)
        {
            XmlSerializer serializer = new XmlSerializer(obj.GetType());

            using TextWriter writer = new StringWriter();
            serializer.Serialize(writer, obj);
            string xml = writer.ToString();

            return Encoding.UTF8.GetBytes(xml);
        }
    }
}
